const mongoose = require('mongoose')
const bcrypt = require('bcrypt-nodejs')
const config = require('../config')
const glob = require('glob')
const { resolve } = require('path')

mongoose.Promise = global.Promise

exports.initDefaultAdminUser = async () => {
  const adminUser = mongoose.model('adminUser')
  await adminUser.deleteMany()
  // 设置默认账户
  let adminUserDefault = await adminUser.findOne({
    userName: config.userAdminDefault.userName
  })
  
  if(!adminUserDefault) {
    // 密码加盐
    const salt = bcrypt.genSaltSync(10)
    const userName = config.userAdminDefault.userName
    const password = bcrypt.hashSync(config.userAdminDefault.password, salt);

    adminUserDefault = await new adminUser({
      userName,
      password,
      avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
      roles: ['admin']
    })

    await adminUserDefault.save()
  }
}

// 加载所有Schema
exports.initAllSchema = () => {
  glob.sync(resolve(__dirname, './schemas', '**/*.js')).forEach(require)
}

exports.connectDatabase = () => {
  let maxConnectTimes = 0

  return new Promise((resolve, reject) => {

    mongoose.connect(config.db, { useNewUrlParser: true })

    mongoose.connection.on('disconnected', () => {
      maxConnectTimes++
      if (maxConnectTimes < 3) {
        mongoose.connect(config.db)
      } else {
        if (reject) {
          reject(err)
        } else {
          throw new Error('数据库断开了~0.0!')
        }
      }
    })

    mongoose.connection.on('error', err => {
      maxConnectTimes++
      if (maxConnectTimes < 3) {
        mongoose.connect(config.db, { useNewUrlParser: true })
      } else {
        if (reject) {
          reject(err)
        } else {
          throw new Error('数据库挂了~0.0!')
        }
      }
    })

    mongoose.connection.once('open', () => {
      console.log('(0.0)数据库连接成功')
      resolve()
    })
    
  })
}
